package lowijs.XfireClient.packet;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import lowijs.XfDroid.FriendDBAdapter;
import android.util.Log;

public class FriendslistPacket extends Packet {
	public FriendslistPacket(byte[] data) {
		ByteBuffer buffer = ByteBuffer.wrap(data);
		buffer.order(ByteOrder.LITTLE_ENDIAN);
		buffer.position(13);

		// add friends
		byte[] charBytes = new byte[32];
		int numFriends = buffer.getShort();
		Log.d("Xfdroid", "Num Friends: " + numFriends);
		Log.d("Xfdroid", "Data Size: " + data.length);

		if (numFriends > 10000) {
			throw new IllegalArgumentException("To many friends! " + numFriends);
		}

		String[] usernames = new String[numFriends];
		for (int i = 0; i < numFriends; i++) {
			int chars = buffer.getShort();

			if (charBytes.length < chars) {
				int len = charBytes.length;
				while (len < chars) {
					len = len << 1;
				}
				charBytes = new byte[len];
			}

			buffer.get(charBytes, 0, chars);
			usernames[i] = new String(charBytes, 0, chars);
		}

		// Go to nick names
		buffer.position(buffer.position() + 9);

		// set friends' nicknames
		String[] nicknames = new String[numFriends];
		for (int i = 0; i < numFriends; i++) {
			int chars = buffer.getShort();

			if (charBytes.length < chars) {
				int len = charBytes.length;
				while (len < chars) {
					len = len << 1;
				}
				charBytes = new byte[len];
			}

			buffer.get(charBytes, 0, chars);
			nicknames[i] = new String(charBytes, 0, chars);
		}

		// Go to userids
		buffer.position(buffer.position() + 11);

		// set friends' userids
		int[] userids = new int[numFriends];
		for (int i = 0; i < numFriends; i++) {
			userids[i] = buffer.getInt();
			Log.d("FriendslistPacket", "Found friend: " + userids[i] + ": " + usernames[i]);
		}

		FriendDBAdapter db = FriendDBAdapter.getInstance(null);
		db.manageFriend(usernames, nicknames, userids);
	}
}
